package com.benjaminwan.read.free.utils

import android.app.Activity
import android.content.Context
import android.location.LocationManager
import android.os.Build
import android.view.WindowManager
import androidx.annotation.StringRes
import com.benjaminwan.read.free.app.App

fun dp2px(value: Int): Int =
    App.INSTANCE.dp2px(value)

fun Context.dp2px(value: Int): Int {
    val scale = resources.displayMetrics.density
    return (value.toFloat() * scale + 0.5f).toInt()
}

fun Activity.dp2px(value: Int): Int {
    return this.applicationContext.dp2px(value)
}

fun Context.getAppVersionCode(): Long {
    var appVersionCode: Long = 0
    try {
        val packageInfo = this.applicationContext
            .packageManager
            .getPackageInfo(this.packageName, 0)
        appVersionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            packageInfo.longVersionCode
        } else {
            packageInfo.versionCode.toLong()
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return appVersionCode
}

fun Context.getAppVersionName(): String {
    var appVersionName = ""
    try {
        val packageInfo = this.applicationContext
            .packageManager
            .getPackageInfo(this.packageName, 0)
        appVersionName = packageInfo.versionName

    } catch (e: Exception) {
        e.printStackTrace()
    }
    return appVersionName
}

fun Activity.setKeepScreenOn() {
    this.window.setFlags(
        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
    )
}

fun Activity.setKeepScreenOnEnable(isEnable: Boolean) {
    if (isEnable) {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    } else {
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
}

/**
 * Gps开关是否启用
 * @return Boolean
 */
fun Context.isGpsEnable(): Boolean {
    val locationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}